import uvicorn
from fastapi import FastAPI
from conf import Item, JenkinsConf
from message import message
from jenkins import Jenkins

app = FastAPI()


@app.post('/code_review')
async def code_review(item: Item):
    if item.action is None:
        return {"success": False, "errorText": "只支持「合并请求相关」操作"}
    # 获取接口数据
    merge_user = item.mergeRequest["user"]  # 合并请求创建人信息
    merge_title, merge_title_url = item.mergeRequest['title'], item.mergeRequest['html_url']  # 合并请求标题、前端地址
    user_name, user_url = merge_user['name'], merge_user['html_url']  # 合并请求创建人姓名、coding主页
    origin_branch, target_branch = item.mergeRequest['head']['ref'], item.mergeRequest['base']['ref']  # 源分支、目标分支
    project_name, project_url = item.repository['name'], item.repository['html_url']  # 项目名称、项目coding主页
    kwargs = {"merge_title": merge_title, "merge_title_url": merge_title_url, "user_name": user_name,
              "user_url": user_url, "origin_branch": origin_branch, "target_branch": target_branch,
              "project_name": project_name, "project_url": project_url}
    if item.action == "create":
        # 发送review通知到钉钉群
        message(**kwargs)
        return {"success": True, "errorText": ""}
    if item.action == "merge":
        # 需要传递给jenkins的数据
        git_url = item.repository.get("ssh_url")  # git clone仓库地址
        job_name = "fvs-common" if target_branch == "master" else "fvs-common-test"  # Jenkins任务名称
        # 初始化Jenkins
        server = Jenkins(url=JenkinsConf.URL, username=JenkinsConf.USER_ID, password=JenkinsConf.API_TOKEN)
        # 组合Jenkins任务参数字典
        params = {"GIT_URL": git_url, "PROJECT_NAME": project_name, "FVS_NAME": "-".join(project_name.split("_")),
                  "USER_NAME": user_name, "MERGE_TITLE": merge_title, "MERGE_URL": merge_title_url}
        # 触发构建任务
        output = server.build_job(name=job_name, parameters=params)
        return {"success": True, "errorText": output}
    else:
        return {"success": False, "errorText": "只支持「合并、创建合并请求」操作"}


if __name__ == '__main__':
    log_config = uvicorn.config.LOGGING_CONFIG
    log_config["formatters"]["access"]["fmt"] = "%(asctime)s - %(levelname)s - %(message)s"
    uvicorn.run(app, log_config=log_config, host="0.0.0.0", port=5000)
